/**
 *  there's will be all function to the module.
 */

$(document).ready(function(){

	$(document).on('click','[data-flash-message-behavior-markAsProcessed]',function(){
		var hash = $(this).parents('div[data-flash-message-hash]').attr('data-flash-message-hash');

		if(hash != undefined) {
			flashMessenger.saveToLocalStorage(hash);
		}
		
		if($(this).parent().find('.message-about-blocking-status').length) {
			location.reload(true);
		}
	});

	$(document).on('click','[data-flash-message-behavior-close]',function(){
		var hash = $(this).parents('div[data-flash-message-hash]').attr('data-flash-message-hash');

		if(hash != undefined) {
			flashMessenger.closeMessage(hash);
		}
	});

	$('body').on('newBlockingMessage closeBlockingMessage', function() {
		flashMessenger.showBlockingMessage();
	});

	$('body').on('flashMessageNew', function(event, data) {
		flashMessenger.onFlashMessageNew(event, data);
	});
	
	$('body').on('flashMessageRemove', function(event, data) {
		flashMessenger.onFlashMessageRemove(event,data);
	});

	$('body').on('mouseover', 'div[data-flash-message-required=no]', function(){
		$(this).clearQueue().stop();
		$(this).css('opacity', '1');
	});

	$('body').on('click', '.big-flash-bg', function() {
		var container = $(this).parents('.big-flash-container:last');
		var closeButton = container.find('.flash-close.big-flash-close');
		if (closeButton != undefined) {
			closeButton.click();
		}
	})

	setInterval(function(){
		flashMessenger.checkLocalStorage();
	}, 5500);

	flashMessenger.loadFlashMessages();
});


var flashMessenger = {

	'blockingMessages' : [],

	'saveToLocalStorage' : function(params){
		var id = JSON.parse(localStorage.getItem('flashID'));
		
		if(id==null){
			id = new Array();
		}

		id.push(params);
		localStorage.setItem('flashID',JSON.stringify(id));
	},	

	'removeFromLocalStorage' : function(params){
		var id = JSON.parse(localStorage.getItem('flashID'));
		var index;
		
		for(var i=0;i<=params.length;i++){
			index = id.indexOf(params[i]);
			if(index >= 0){
				id.splice(index, 1);
			}
		}

		localStorage.setItem('flashID',JSON.stringify(id));
		
	},
	
	'checkLocalStorage' : function() {
		var that = this;
		var id = JSON.parse(localStorage.getItem('flashID'));

		if(id != null && id.length > 0){
			var idToSend = id.join(',');

			$.ajax({
				type:'POST',
				url: '~flashMessages.deleteList',
				data: {'list':idToSend},
				success: function(data){
					var ids = JSON.parse(data);
					if (ids.length > 0) {
						that.removeFromLocalStorage(ids);
					}
				}
			});
		}
	},

	'loadFlashMessages' : function() {
		var that = this;
		//$.get('/flashMessages/messages/list', {}, function(data) {
		//	$(data).find('div.flash-element').each(function(index, messageBlock){
		//		that.addMessage(messageBlock);
		//	});
		//});
		$('#flash-container').find('div.flash-element').each(function(index, messageBlock){
			that.addMessage(messageBlock);
		});
	},

	/**
	 * Добавляет сообщение на страницу
	 *
	 * @param messageBlock - ($.parseHTML('<div>...</div>');)
	 */
	'addMessage' : function (messageBlock) {
		var that = this;
		var messageType = $(messageBlock).attr('data-type-message');
		var messageHash = $(messageBlock).attr('data-flash-message-hash');
		var messageIsRequired = $(messageBlock).attr('data-flash-message-required') == 'yes';
		var isBlocking = messageType == 'blocking';

		if (this.existsInLocalStorage(messageHash) || this.existsInDisplayQueue(messageHash)) {
			return;
		}

		switch (messageType) {
			case "blocking":
				this.addBlockingMessage(messageBlock);
				break;
			case "notBlocking":
				this.addNotBlockingMessage(messageBlock);
				break;
		}

		if (!messageIsRequired && !isBlocking) {
			setInterval(function(){
				that.fadeMessage(messageHash);
			}, 10000);
		}
	},

	'fadeMessage' : function (messageHash) {
		var that = this;

		$('[data-flash-message-hash=' + messageHash + ']').animate(
			{
				opacity : 0
			},
			{
				duration : 5000,
				complete : function() {
					that.closeMessage(messageHash);
				}
			}
		);
	},

	'addNotBlockingMessage' : function (html) {
		$('div.small-flash-container').append(html);
	},

	'addBlockingMessage' : function (html) {
		this.blockingMessages.push(html);
		$('body').trigger('newBlockingMessage');
	},

	'showBlockingMessage' : function () {
		var blockContent = $('div.big-flash-wrapper').html();

		if (blockContent.length > 0 || this.blockingMessages.length == 0) {
			return;
		}

		var html = this.blockingMessages.shift();
		$('div.big-flash-wrapper').html(html);
		$('div.big-flash-container').show();
	},

	'closeMessage' : function (messageHash) {
		var poolIndex = this.getBlockedMessagePoolIndex(messageHash);

		if (poolIndex > -1) {
			this.blockingMessages.splice(poolIndex, 1);
			return;
		}

		var messageBlock = $('div[data-flash-message-hash=' + messageHash + ']');
		var type = messageBlock.attr('data-type-message');

		messageBlock.remove();

		if (type == 'blocking') {
			$('div.big-flash-container').hide();
			$('body').trigger('closeBlockingMessage');
		}
	},

	'existsInLocalStorage' : function (hash) {
		var list = JSON.parse(localStorage.getItem('flashID'));
		return (list != null) && ($.inArray(hash, list) != -1);
	},

	'existsInDisplayQueue' : function (messageHash) {
		var length = 0;

		var existingElement = $(".small-flash-container [data-flash-message-hash='" + messageHash + "']");
		length += existingElement.length;

		existingElement = $(".big-flash-container [data-flash-message-hash='" + messageHash + "']");
		length += existingElement.length;

		if (length > 0) {
			return true;
		}

		return this.getBlockedMessagePoolIndex(messageHash) > -1;

	},

	'getBlockedMessagePoolIndex' : function (messageHash) {
		var poolIndex = -1;

		$.each(this.blockingMessages, function(index, data){
			var id = $(data).attr('data-flash-message-hash');
			if (id == messageHash) {
				poolIndex = index;
			}
		});

		return poolIndex;
	},

	'onFlashMessageNew' : function(event, data) {
		var that = this;

		$.get('~flashMessages.messages.item',
			{id: data.flashMessageId},
			function(data){
				var message = $.parseHTML(data);

				var flashMessageLoaded = $.Event('flashMessageLoaded', { item: data, cancel: false });
				$('body').trigger(flashMessageLoaded);

				if (flashMessageLoaded.cancel) {
					var hash = $(data).attr('data-flash-message-hash');
					that.saveToLocalStorage(hash);
					return;
				}

				that.addMessage(message);
			}
		);
	},

	'onFlashMessageRemove' : function(event, data) {
		this.closeMessage(data.flashMessageHash);
	}
	
}
